

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>表单组合</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="/static/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="/static/layuiadmin/style/admin.css" media="all">
</head>
<body>


<div class="layui-fluid">

  <div class="layui-card">

    <div class="layui-tab layui-tab-brief" lay-filter="novel">

      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="1">小说信息</li>
        <li lay-id="2">章节目录</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row layui-col-space15">

            <div class="layui-card-body" style="padding: 15px;">
                <form class="layui-form" action="" lay-filter="component-form-group">

                  <div class="layui-form-item">
                      <label class="layui-form-label">小说ID</label>
                      <div class="layui-input-block">
                        <input type="tel" name="id" lay-verify="required" style="background-color: #FBFBFB;" autocomplete="off" class="layui-input" value="{$novel.id}" disabled>
                      </div>
                  </div>

                  <div class="layui-form-item">
                    <label class="layui-form-label">后台书名</label>
                    <div class="layui-input-block">
                      <input type="text" name="title" lay-verify="required|title" autocomplete="off" class="layui-input" value="{$novel.title}">
                    </div>
                  </div>

                  <div class="layui-form-item">
                      <label class="layui-form-label">前台书名</label>
                      <div class="layui-input-block">
                        <input type="text" name="origin_title" autocomplete="off" class="layui-input" value="{$novel.origin_title}">
                      </div>
                  </div>

                  <div class="layui-form-item">
                      <label class="layui-form-label">作者</label>
                      <div class="layui-input-block">
                        <input type="text" name="author" lay-verify="required|title" placeholder="请输入" autocomplete="off" class="layui-input" value="{$novel.author}">
                      </div>
                  </div>


                  <div class="layui-form-item">
                    <label class="layui-form-label">主角</label>
                    <div class="layui-input-block">
                      <input type="text" name="lead"  placeholder="逗号分割" autocomplete="off" class="layui-input" value="{$novel.lead}">
                    </div>
                  </div>

                  <div class="layui-form-item">
                    <label class="layui-form-label">封面图片</label>
                    <div class="layui-input-block" style="padding-bottom: 15px;">
                      <div class="layui-upload-drag" id="cover">
                        <div id="cover_head" {if $novel.cover}class="layui-hide"{/if}>
                        <i class="layui-icon"></i>
                        <p>点击上传，或将文件拖拽到此处</p>
                      </div>
                      <div {if !$novel.cover}class="layui-hide"{/if} id="uploadDemoView">
                        <img src="{$novel.cover_text}" alt="上传成功后渲染" style="max-width: 128px;width: 128px;">
                        <input type="hidden" name="cover" value="{$novel.cover}">
                      </div>
                    </div>
                  </div>



          <div class="layui-form-item">
            <label class="layui-form-label">上架状态</label>
            <div class="layui-input-block">
              <input type="radio" name="in_shelf" value="1" title="上架" {if $novel.in_shelf == 1}checked{/if}>
              <input type="radio" name="in_shelf" value="2" title="下架" {if $novel.in_shelf == 2}checked{/if}>
              <input type="radio" name="in_shelf" value="0" title="绝对下架" {if $novel.in_shelf == 0}checked{/if}>
            </div>
            <div class="layui-form-mid layui-word-aux">
              下架：读者书架照常展示其他推荐位隐藏，绝对下架：所有推荐位都不展示。上下架状态对已提取链接、App开屏无效。
            </div>
          </div>

              <div class="layui-form-item">
                <label class="layui-form-label">更新状态</label>
                <div class="layui-input-block">
                  <div class="layui-inline">
                    <select name="update_status" lay-verify="required" >
                      <option value="0" {if $novel.update_status == 0}selected{/if}>连载</option>
                      <option value="1" {if $novel.update_status == 1}selected{/if}>完结</option>
                      <option value="2" {if $novel.update_status == 2}selected{/if}>弃更</option>
                    </select>
                  </div>
                </div>
              </div>


              <div class="layui-form-item">
                <label class="layui-form-label">书籍评级</label>
                <div class="layui-input-block">
                  <div class="layui-inline">
                    <select name="scale"  lay-verify="required" >
                      <option value="C" {if $novel.scale == 'C'}selected{/if}>C级别</option>
                      <option value="B" {if $novel.scale == 'B'}selected{/if}>B级别</option>
                      <option value="A" {if $novel.scale == 'A'}selected{/if}>A级别</option>
                      <option value="S" {if $novel.scale == 'S'}selected{/if}>S级别</option>
                    </select>
                  </div>
                  <div class="layui-inline">
                    <div class="layui-form-mid layui-word-aux">从C级别到S级评级依次递增</div>
                  </div>
                </div>
              </div>


              <div class="layui-form-item">
                <label class="layui-form-label">频道分类</label>
                <div class="layui-input-block">
                  <div class="layui-inline">
                    <select name="freq_id" id="freq_id"  lay-verify="required" lay-filter="freq">
                      <option value="">请选择频道</option>
                      {foreach $freq as $k => $v}
                      <option value="{$v.id}" {if $novel.freq_id == $v.id}selected{/if}>{$v.name}</option>
                      {/foreach}
                    </select>
                  </div>

                  <div class="layui-inline">
                    <select name="class_id" id="class_id" lay-verify="required" id="class_id" lay-search lay-filter="class">
                      <option value="">请选择分类</option>
                      {foreach $freq as $k => $v}
                      {if $v.id == $novel.freq_id}
                      {foreach $v.sonClass as $i}
                      <option value="{$i.id}" {if $novel.class_id == $i.id}selected{/if}>{$i.name}</option>
                      {/foreach}
                      {/if}
                      {/foreach}
                    </select>
                  </div>
                </div>
              </div>


              <div class="layui-form-item">
                <label class="layui-form-label">子分类</label>
                <div class="layui-input-block">
                  <div class="layui-inline">
                    <select name="son_class_id" id="son_class_id" lay-verify="required" lay-search>
                    <option value="">请选择子分类</option>
                      {foreach $sonClass as $v}
                      <option value="{$v.id}" {if $novel.son_class_id == $v.id}selected{/if}>{$v.name}</option>
                      {/foreach}
                    </select>
                  </div>
                  <div class="layui-inline">
                    <div class="layui-form-mid layui-word-aux">前台子标签</div>
                  </div>
                </div>
              </div>


              <div class="layui-form-item">
                <label class="layui-form-label">后台标签</label>
                <div class="layui-input-block">
                  {foreach $labels as $k => $v}
                  <input type="checkbox" name="label[]" title="{$v.name}" value="{$v.id}" {if $v.have == 1}checked{/if}>
                  {/foreach}
                </div>
              </div>

              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">推荐加桌</label>
                  <div class="layui-input-inline">
                    <input type="number" name="recom_chapter" autocomplete="off" class="layui-input" value="{if $novel.recom_chapter > 0}{$novel.recom_chapter}{/if}">
                  </div>
                  <div class="layui-inline">
                    <div class="layui-form-mid layui-word-aux">推荐加桌章节，用于客户提取链接页面显示，可不填</div>
                  </div>
                </div>
              </div>

              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">千字/书币</label>
                  <div class="layui-input-inline">
                    <input type="number" name="words_fee" lay-verify="required" autocomplete="off" class="layui-input" value="{$novel.words_fee}">
                  </div>
                </div>
              </div>


              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">章节更新</label>
                  <div class="layui-input-inline">
                    <input type="text" name="chapter_up_time" style="background-color: #FBFBFB;" autocomplete="off" class="layui-input" value="{$novel.chapter_up_time}" disabled>
                  </div>
                </div>
              </div>

              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">字数</label>
                  <div class="layui-input-inline">
                    <input type="tel" name="number_words" style="background-color: #FBFBFB;" autocomplete="off" class="layui-input" value="{$novel.number_words}" disabled>
                  </div>
                </div>
              </div>


              <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简介</label>
                <div class="layui-input-block">
                  <textarea name="brief" lay-verify="required" placeholder="请输入内容" class="layui-textarea">{$novel.brief}</textarea>
                </div>
              </div>


              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">续传</label>
                  <div class="layui-input-block">
                    <div class="layui-btn-container">
                      <button type="button" class="layui-btn layui-btn-normal" id="xcFile">选择文件</button>
                      <button type="button" class="layui-btn" id="xcFileRun">上传保存</button>
                    </div>
                    <div class="layui-inline">
                      <div class="layui-form-mid layui-word-aux">只添加网站未有章节，文件内容还是从第一章开始</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">覆盖</label>
                  <div class="layui-input-block">
                    <div class="layui-btn-container">
                      <button type="button" class="layui-btn layui-btn-normal" id="fgFile">选择文件</button>
                      <button type="button" class="layui-btn" id="fgFileRun">上传保存</button>
                    </div>
                    <div class="layui-inline">
                      <div class="layui-form-mid layui-word-aux">覆盖已存在章节并添加新章节（不删章节）</div>
                    </div>
                  </div>
                </div>
              </div>



              <div class="layui-form-item layui-layout-admin">
                <div class="layui-input-block">
                  <div class="layui-footer" style="left: 0;">
                    <button class="layui-btn" lay-submit="" lay-filter="component-form-demo1">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                  </div>
                </div>
              </div>
              </form>
            </div></div>


      </div></div>

      <div class="layui-tab-item">
        <div class="layui-card-body">
          <table id="LAY-user-back-role" lay-filter="LAY-user-back-role"></table>


          <script type="text/html" id="payTpl">
            {{#  if(d.is_pay == 0){ }}
            免费
            {{#  } else if(d.is_pay == 1) { }}
            <span style="color: red;">收费</span>
            {{#  } }}
          </script>

          <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
              <button class="layui-btn layui-btn-sm" lay-event="add">添加章节</button>
            </div>
          </script>

          <script type="text/html" id="table-useradmin-admin">
            <a class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
            <a class="layui-btn layui-btn-primary layui-border-green layui-btn-xs" lay-event="preview"><i class="layui-icon layui-icon-search"></i>预览</a>
          </script>
        </div>
      </div>

      </div>
    </div>

  </div>

</div>


<script src="/static/layuiadmin/layui/layui.js"></script>
<script>
  layui.config({
    base: '/static/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index', 'form','element','table'], function(){
    var $ = layui.$
            ,admin = layui.admin
            ,layer = layui.layer
            ,form = layui.form
            ,upload = layui.upload
            ,element = layui.element
            ,table = layui.table;

    form.render(null, 'component-form-group');




    table.render({
      elem: '#LAY-user-back-role'
      , url: '/novel/directory?nid={$novel.id}' //模拟接口
      ,height: 'full-100'
      , response: {
        statusCode: 1
      }
      ,initSort: {
        field: 'chapter_no' //排序字段，对应 cols 设定的各字段名
        ,type: 'asc'
      }
      ,autoSort: false //禁用前端自动排序
      , page: true //开启分页
      ,limit: 20
      , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
      , defaultToolbar: false
      , cols: [[
        {field: 'id', width: 80, title: 'ID'}
        , {field: 'name',minWidth: 400, title: '标题'}
        , {field: 'chapter_no', minWidth: 80, title: '序号', align: 'center', sort: true}
        , {field: 'update_time',minWidth: 180, title: '更新时间'}
        , {field: 'is_pay', title: '是否收费', templet: '#payTpl',align: 'center',minWidth: 100}
        , {field: 'words', minWidth: 80, title: '字数', align: 'center'}
        , {title: '操作', minWidth: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin'}
      ]]
    });

    //头工具栏事件
    table.on('toolbar(LAY-user-back-role)', function (obj) {
      switch (obj.event) {
        case 'add':
          layer.open({
            type: 2
            , title: '添加章节'
            , content: '/novel/chapterForm.html?novel_id={$novel.id}'
            , maxmin: true //开启最大化最小化按钮
            , offset: '15px'
            , area: ['40%', '90%']
            , btn: ['确定', '取消']
            ,yes: function(index, layero){
              var iframeWindow = window['layui-layer-iframe'+ index]
                      ,submit = layero.find('iframe').contents().find("#LAY-user-role-submit");

              //监听提交
              iframeWindow.layui.form.on('submit(LAY-user-role-submit)', function(data){
                var field = data.field; //获取提交的字段
                //提交 Ajax 成功后，静态更新表格中的数据
                //$.ajax({});
                admin.req({
                  url: '/novel/setChapter'
                  , type: "POST"
                  , data: field
                  , done: function (res) {
                    layer.msg('添加成功', {icon: 1, time: 1000}, function () {
                      table.reload('LAY-user-back-role');
                      layer.close(index); //关闭弹层
                    });
                  },not_finish:function (res) {
                    layer.msg(res.msg);
                  }
                });

              });
              submit.trigger('click');
            }
          });
          break;
      }
    });

    //监听行工具事件
    table.on('tool(LAY-user-back-role)', function(obj){
      var data = obj.data;
      if(obj.event === 'edit'){
        var tr = $(obj.tr);
        layer.open({
          type: 2
          , title: '修改章节'
          , offset: '15px'
          , content: '/novel/chapterForm.html?novel_id=' + data.novel_id + '&chapter_no=' + data.chapter_no
          , maxmin: true //开启最大化最小化按钮
          , area: ['40%', '90%']
          , btn: ['确定', '取消']
          ,yes: function(index, layero){
            var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submit = layero.find('iframe').contents().find("#LAY-user-role-submit");

            //监听提交
            iframeWindow.layui.form.on('submit(LAY-user-role-submit)', function(data){
              var field = data.field; //获取提交的字段
              //提交 Ajax 成功后，静态更新表格中的数据
              //$.ajax({});
              admin.req({
                url: '/novel/setChapter'
                , type: "POST"
                , data: field
                , done: function (res) {
                  layer.msg('修改成功', {icon: 1, time: 1000}, function () {
                    table.reload('LAY-user-back-role');
                    layer.close(index); //关闭弹层
                  });
                },not_finish:function (res) {
                  layer.msg(res.msg);
                }
              });
            });
            submit.trigger('click');
          }
        });
      }else if(obj.event === 'preview'){
        layer.open({
          type: 2,
          title: '预览',
          shadeClose: true,
          shade: 0.5,
          maxmin: true, //开启最大化最小化按钮
          area: ['40%', '90%'],
          content: '/novel/preview?novel_id=' + obj.data.novel_id + '&chapter_no=' + obj.data.chapter_no
        });
      }
    });

    //触发排序事件
    table.on('sort(LAY-user-back-role)', function(obj){ //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      console.log(obj.field); //当前排序的字段名
      console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
      console.log(this); //当前排序的 th 对象

      //尽管我们的 table 自带排序功能，但并没有请求服务端。
      //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
      table.reload('LAY-user-back-role', {
        initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
        ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
          field: obj.field //排序字段
          ,order: obj.type //排序方式
        }
        ,page: {
          curr: 1  // 将页码重置为第一页
        }
      });
      //layer.msg('服务端排序。order by '+ obj.field + ' ' + obj.type);
    });



    form.on('select(freq)', function(data){
      var freqJson = '{$freqJson}';
      var freq = JSON.parse(HTMLDecode(freqJson));
      var class_id = '{$novel.class_id}';
      console.log(freq);
      console.log(data.value); //得到被选中的值
      if (data.value === '') {
        var html = "<option value=''>请选择分类</option>";
        for (var i = 0, l = freq.length; i < l; i++) {
          for (var x = 0, y = freq[i]['sonClass'].length; x < y; x++) {
            if (freq[i]['sonClass'][x]['id'] == class_id){
              html += "<option value='" + freq[i]['sonClass'][x]['id'] + "' selected>" + freq[i]['sonClass'][x]['name'] + "</option>";
            }else {
              html += "<option value='" + freq[i]['sonClass'][x]['id'] + "'>" + freq[i]['sonClass'][x]['name'] + "</option>";
            }
          }
          $("#class_id").html(html);
          form.render();
        }
      }else {
        for (var i = 0, l = freq.length; i < l; i++) {
          if (freq[i]['id'] == data.value) {
            var html = "<option value=''>请选择分类</option>";
            for (var x = 0, y = freq[i]['sonClass'].length; x < y; x++) {
              console.log(freq[i]['sonClass'][x]);
              if (freq[i]['sonClass'][x]['id'] == class_id) {
                html += "<option value='" + freq[i]['sonClass'][x]['id'] + "' selected>" + freq[i]['sonClass'][x]['name'] + "</option>";
              } else {
                html += "<option value='" + freq[i]['sonClass'][x]['id'] + "'>" + freq[i]['sonClass'][x]['name'] + "</option>";
              }
            }
            $("#class_id").html(html);
            form.render(null, 'component-form-group');
          }
        }
      }
      getSelectClassSon();
    });


    form.on('select(class)', function (data) {
      getSelectClassSon();
    });

    function getSelectClassSon(){

      var freqId = $("#freq_id").val();
      var classId = $("#class_id").val();
      admin.req({
        url: '/novel/getSelectClassSon'
        , type: "POST"
        , data: {'freq_id': freqId, 'class_id': classId}
        , done: function (res) {
          var select = document.getElementById("son_class_id");
          select.options.length = 0;

          var option = document.createElement("option");
          option.value = '';
          option.text = '请选择子分类'
          select.appendChild(option);
          for (var i = 0; i < res.data.length; i++) {
            var option = document.createElement("option");
            option.value = res.data[i].id;
            option.text = res.data[i].name;
            select.appendChild(option);
          }
          $("#son_class_id").val('{$novel.son_class_id}');
          form.render();
        }, not_finish: function (res) {
          layer.msg(res.msg);
        }
      });



    }

    //拖拽上传
    upload.render({
      elem: '#cover'
      ,accept:'images'
      ,acceptMime: 'image/jpeg, image/png'
      ,url: '/tool/uploadPic' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
      ,done: function(res){
        if (res.code === 1){
          layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data.picUrl);
          layui.$('#uploadDemoView').find('input').val(res.data.filePath);
          layui.$('#cover_head').addClass('layui-hide');
          console.log(res)
        }else {
          layer.msg(res.msg);
        }
      }
    });


    //选完文件后不自动上传
    upload.render({
      elem: '#xcFile'
      ,accept:'file'
      ,acceptMime: 'text/*'
      ,url: '/novel/upload?id={$novel.id}&type=1'
      ,auto: false
      //,multiple: true
      ,bindAction: '#xcFileRun'
      ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
        layer.load(); //上传loading
      }
      ,error: function(index, upload){
        layer.closeAll('loading');
      }
      ,done: function(res){
        layer.closeAll('loading');
        if (res.code === 1){
          layer.msg('章节续传成功', {icon: 1, time: 2000}, function () {
            location.reload();
          });
        }else {
          layer.msg(res.msg);
        }
      }
    });

    upload.render({
      elem: '#fgFile'
      ,accept:'file'
      ,acceptMime: 'text/*'
      ,url: '/novel/upload?id={$novel.id}&type=2'
      ,auto: false
      //,multiple: true
      ,bindAction: '#fgFileRun'
      ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
        layer.load(); //上传loading
      }
      ,error: function(index, upload){
        layer.closeAll('loading');
      }
      ,done: function(res){
        layer.closeAll('loading'); //关闭loading
        if (res.code === 1){
          layer.msg('章节覆盖成功', {icon: 1, time: 2000}, function () {
            location.reload();
          });
        }else {
          layer.msg(res.msg);
        }
      }
    });


    /* 自定义验证规则 */
    form.verify({
      title: function(value){
        if(value.length > 40){
          //return '字数过长';
        }
      }
      ,pass: [/(.+){6,12}$/, '密码必须6到12位']
      ,content: function(value){
        layedit.sync(editIndex);
      }
    });


    /* 监听提交 */
    form.on('submit(component-form-demo1)', function(data){
      admin.req({
        url: '/novel/edit'
        , type: "POST"
        , data: data.field
        , done: function (res) {
          layer.msg('修改成功', {icon: 1, time: 1000}, function () {
          });
        }, not_finish: function (res) {
          layer.msg(res.msg);
        }
      });
      return false;
    });

    function HTMLDecode(text) {
      var temp = document.createElement("em");
      temp.innerHTML = text;
      var output = temp.innerText || temp.textContent;
      temp = null;
      return output;
    }


    //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
    var layid = location.hash.replace(/^#novel=/, '');
    element.tabChange('novel', layid); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项

    //监听Tab切换，以改变地址hash值
    element.on('tab(novel)', function(){
      location.hash = 'novel='+ this.getAttribute('lay-id');
    });


  });
</script>
</body>
</html>
